import React, { Component } from "react"
import { connect } from 'react-redux'
import { messages, queryCurrencyPrecision } from "share/common"
import Selector from "components/selector"
import { Row, Form, Col, Spin, message } from "antd"
import AlipayImg from "images/loan-billing/alipay.svg"
import BankImg from "images/loan-billing/bank.svg"
import queryService from "../bank-query/query.service"
import 'styles/pay/bank-hoc.scss'

@connect(mapStateToProps)
class BankHoc extends Component {

  componentDidMount () {
    const { onRef } = this.props;
    onRef && onRef(this.selectorRef);
  }

  state = {
    bankInfo: undefined,
    surplusLoading: false,
    surplus: null
  };

  handleBanKChange = value => {
    this.setState({ bankInfo: value, surplus: null }, () => {
      this.props.onChangeBank(value);
    });
  };

  getSurplus = () => {
    const { bankInfo } = this.state;
    this.setState({ surplusLoading: true });
    queryService.queryAccountBalance([{
      id: bankInfo.id,
      acctNo: bankInfo.companyBank.bankAccountNumber,
      acctName: bankInfo.companyBank.bankAccountName,
      channel: bankInfo.bankPayInfo.vendor
    }]).then(res => {
      let surplus = res.data.find(item => item.id === bankInfo.id).accountBalance;
      this.setState({ surplusLoading: false, surplus });
    }).catch(e => {
      this.setState({ surplusLoading: false });
      message.error(e.response.data.message);
    })
  };

  render () {
    const { searchParams, radioValue, loginUser } = this.props;
    const { bankInfo, surplusLoading, surplus } = this.state;
    const style = { width: '20px', marginRight: '8px' };
    return (
      <Row gutter={10}>
        <Col span={8}>
          <Form.Item
            required
            className={'bank-form'}
            style={{ marginBottom: '0' }}
            label={messages('finance-4.key192')/*付款账户*/}
            {...{
              labelCol: { span: 6 },
              wrapperCol: { span: 18 },
            }}
          >
            <Selector
              selectorItem={{
                url: `/api/companyBankAuth/getAuthCompanyBank/${loginUser.userOID}`,
                label: item => item.companyBank.bankAccountName,
                key: item => item.companyBank.bankAccountNumber,
                showSearchLabel: item => (
                  <div>
                    {<img src={item.bankPayInfo && item.bankPayInfo.vendor === 'ALIPAY' ? AlipayImg : BankImg}
                          style={style}/>}
                    {`${item.companyBank.bankAccountName} - ${item.companyBank.bankAccountNumber}${item.companyBank.bankBranchName ? ` - ${item.companyBank.bankBranchName}` : ''}`}
                    {item.bankPayInfo && item.bankPayInfo.status === 'Y'&& item.accountType !== 'ALIPAY_LOGON_ID' && (
                      <span style={{ color: "#108ee9" }}>{messages('finance-4.key193')/*（银企直联生效中）*/}</span>
                    )}
                  </div>
                ),
                dynamicUrl: true
              }}
              onRef={ref => this.selectorRef = ref}
              params={{
                setOfBooksId: searchParams.setOfBookId,
                paymentMethodCode: radioValue || 'default',
                currency: searchParams.currencyCode || undefined,
                companyId: searchParams.paymentCompanyId
              }}
              entity
              value={bankInfo}
              allowClear={false}
              firstOptionToValue
              onChange={this.handleBanKChange}
            />
          </Form.Item>
        </Col>
        <Col span={8}>
          {
            bankInfo && bankInfo.bankPayInfo && bankInfo.bankPayInfo.status === 'Y'&& bankInfo.accountType !== 'ALIPAY_LOGON_ID' && (
              <span style={{ lineHeight: '32px' }}>
                <Col span={6} style={{ textAlign: 'right', color: '#1e2126' }}>{messages('finance-4.key194')/*账户余额：*/}</Col>
                <Col span={18}>
                  {bankInfo.companyBank.currencyCode}
                  <span style={{ marginLeft: '8px' }}>
                    {
                      surplusLoading ? <Spin/> : (
                        typeof surplus === 'number' ? this.filterMoney(surplus, queryCurrencyPrecision(bankInfo.companyBank.currencyCode)) :
                          <a onClick={this.getSurplus}>{messages('finance-4.key54')/*查询余额*/}</a>
                      )
                    }
                  </span>
                </Col>
              </span>
            )
          }
        </Col>
      </Row>
    )
  }

}

function mapStateToProps (state) {
  return {
    loginUser: state.login.loginUser
  }
}

export default BankHoc
